package com.googlecode.restitory.gae.hook;

import com.googlecode.restitory.gae.Request;
import com.googlecode.restitory.gae.Response;
import com.googlecode.restitory.gae.TextContent;

public class CallbackHook implements Hook {

	@Override
	public Response execute(Request request, Chain chain) {
		String callback = request.getParams().getFirst("callback");
		if (callback == null) {
			callback = "";
		}
		callback = callback.trim();
		Response ret = chain.execute(request);
		if (ret == null) {
			return null;
		}
		String contentType = ret.getContentType();
		if (callback.length() > 0
				&& contentType != null
				&& (contentType.startsWith("application/javascript") || contentType
						.startsWith("application/json"))) {
			char[] chars = ((TextContent) ret.getContent()).getValue();
			StringBuilder sb = new StringBuilder(chars.length
					+ callback.length() + 3).append(callback).append('(')
					.append(chars).append(");");
			chars = new char[sb.length()];
			sb.getChars(0, chars.length, chars, 0);
			return ret.copy().setContentType("application/javascript")
					.setContent(chars);
		}
		return ret;
	}
}
